<?php
/**
 * 微信受理模式
 */
namespace app\components\pay;

use Yii;

use app\models\Order;
use app\models\OrderPay;
use app\components\Func;
use app\components\KelaileJava;
use app\models\App;
use app\models\AppBind;
use app\models\StudentOrder;
use app\models\StudentVipMembers;
use app\models\WxAppletOrders;
use app\models\CommodityLibs;
use app\models\OrdersCommodity;

class WxAcceptPay extends Pay {

	const PREPAY_URL = 'superpay/nativepay'; //主扫
    const QRPAY_URL = 'superpay/micropay'; //被扫
    const REFUND = 'superpay/refund'; //退款
    const QUERY_URL = 'superpay/query'; //查询
    const WX_AUTH_CODE_GET_OPENID = 'superpay/getOpenId';

    public $appid; //主账号appid
    public $mch_id; //主账号mch_id
    public $sub_appid; //商家appid
    public $sub_mch_id; //商家mch_id
    public $mch_key; //受理key

    public function __construct($appid, $mch_id, $sub_appid, $sub_mch_id, $mch_key = '') {
    	$this->appid = $appid;
    	$this->mch_id = $mch_id;
    	$this->sub_appid = $sub_appid;
        $this->sub_mch_id = $sub_mch_id;
    	$this->mch_key = $mch_key;
    }

    public function prepay(array $params) {

    }

    //根据支付码获取openid
    public function authcodeToOpenid(array $paras) {
        $paras['account_info'] = [
            $paras['pay_type'] => [
                'wx_appid' => $this->appid,
                'mch_id' => $this->mch_id,
                'wx_sub_appid' => $this->sub_appid,
                'sub_mch_id' => $this->sub_mch_id,
                'mch_key' => $this->mch_key,
            ],
        ];
        unset($paras['pay_type']);
        $javaRes = self::getResBuyJavaApi(self::WX_AUTH_CODE_GET_OPENID, $paras);
        return $javaRes;
    }

    //刷卡支付
    public function micropay(array $params) {
    	if(!isset($params['device_no'])) throw new \Exception('device_no为空');
        if(!isset($params['out_trade_no'])) throw new \Exception('out_trade_no为空');
        if(!isset($params['total_fee'])) throw new \Exception('total_fee为空');
        if(!isset($params['auth_code'])) throw new \Exception('auth_code为空');
        if(!isset($params['body'])) throw new \Exception('body为空');
        $params['notify_url'] = $this->notifyurl();
        if(empty($this->sub_appid)){//没有配置公众号的情况
            $params['account_info'] = [
                $params['pay_type'] => [
                    'wx_appid' => $this->appid,
                    'mch_id' => $this->mch_id,
                    'sub_mch_id' => $this->sub_mch_id,
                    'mch_key' => $this->mch_key,
                ],
            ];    
        }else{
            $params['account_info'] = [
                $params['pay_type'] => [
                    'wx_appid' => $this->appid,
                    'mch_id' => $this->mch_id,
                    'wx_sub_appid' => $this->sub_appid,
                    'sub_mch_id' => $this->sub_mch_id,
                    'mch_key' => $this->mch_key,
                ],
            ];
        }
        unset($params['pay_type']);
        $javaRes = self::getResBuyJavaApi(self::QRPAY_URL, $params);
        return $javaRes;
    }

    /**
     * 支付成功
     * @param array $postArr java返回的数据
     */
    public static function paySuccess($postArr, $order) {
        if($postArr['pay_type'] == KelaileJava::CITIC_WX) $payType = OrderPay::PAY_TYPE_CITIC_WX;
    	if($postArr['pay_type'] == KelaileJava::WEIXIN_PAY) $payType = OrderPay::PAY_TYPE_WX;
    	$order->pay_type = $payType;
        $order->status = ($postArr['pay_status'] == '1') ? Order::STATUS_PAY_END : Order::STATUS_PAY_FAIL;
        //$order->out_trade_no = $postArr['transaction_id']; //交易流水号
        $order->ptime = $postArr['pay_time'];
        $order->third_discount_fee += $postArr['ent_discount_fee']; //商家优惠
        $order->third_pay_discount_fee += $postArr['discount_fee']; //支付平台补贴
        $order->saveRedis();

        //未支付成功
        if($postArr['pay_status'] != '1') throw new \Exception($postArr['pay_msg']);

        $orderPay = new OrderPay();
        $orderPay->order_id = $order->id;
        $orderPay->enterprise_id = $order->enterprise_id;
        $orderPay->shop_id = $order->shop_id;
        $orderPay->befrom = $order->befrom;
        $orderPay->device_no = $order->device_no;
        $orderPay->cashier_id = $order->cashier_id;
        $orderPay->pay_type = $payType;
        $orderPay->pay_fee = $postArr['receipt_amount']; //商家实收金额
        $orderPay->payee = $postArr['account'];  //收款人
        $orderPay->payer = $postArr['payer'];    //付款人
        $orderPay->trade_id = $postArr['transaction_id'];//交易流水号
        $orderPay->utime = $postArr['pay_time'];
        $orderPay->discount_fee = $order->discount_fee;
        $orderPay->third_discount_fee = $order->third_discount_fee;
        $orderPay->saveRedis();

    }

    //定单查询
    public function orderquery(array $paras) {
        if(!isset($paras['out_trade_no']))throw new \Exception('out_trade_no为空',2022015);
        if(!isset($paras['is_push']))$paras['is_push'] = 'false';
        return self::getResBuyJavaApi(self::QUERY_URL, $paras);
    }

    //退款
    public function refund(array $params) {
        if(!isset($params['out_trade_no'])) throw new \Exception('out_trade_no为空',2022015);
        if(!isset($params['refund_amount'])) throw new \Exception('refund_amount为空',2022021);
        if(!isset($params['refund_reason'])) throw new \Exception('refund_reason为空',2022022);  //退款原因:设备号,标识客来乐设备退款
        if(!isset($params['total_fee'])) throw new \Exception('total_fee为空');
        if(empty($this->sub_appid)){
            $params['account_info'] = [
                $params['pay_type'] => [
                    'wx_appid' => $this->appid,
                    'mch_id' => $this->mch_id,
                    'sub_mch_id' => $this->sub_mch_id,
                    'mch_key' => $this->mch_key,
                ],
            ];
        }else{
            $params['account_info'] = [
                $params['pay_type'] => [
                    'wx_appid' => $this->appid,
                    'mch_id' => $this->mch_id,
                    'wx_sub_appid' => $this->sub_appid,
                    'sub_mch_id' => $this->sub_mch_id,
                    'mch_key' => $this->mch_key,
                ],
            ];
        }
        unset($params['pay_type']);
        $javaRes = self::getResBuyJavaApi(self::REFUND, $params);
        if($javaRes['res']['status'] != '1') throw new \Exception($javaRes['res']['sub_msg']);
        return [
            'refund_trade_no' => $javaRes['res']['refund_trade_no'], //java生成
            'refund_trade_id' => $javaRes['res']['transaction_id'], //退款交易流水号
        ];
    }

    public function refundquery(array $params) {
    }

    public function cancel(array $params) {
    }

    /**
     *  作用：生成签名
     */
    public function getSign($Obj)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[$k] = (string)$v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters, SORT_STRING);

        //$String = $this->formatBizQueryParaMap($Parameters, false);
        $String = Func::http_build_str($Parameters);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".$this->mch_key;
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    public function checkNotifySign($params) {
        return true;
        /*$sign = $params['sign'];
        unset($params['sign']);
        return $sign == $this->getSign($arr);*/
    }

    //获取支付成功通知url
    public function notifyurl() {
        return Func::getHostInfo() . '/' . KelaileJava::NOTIFY_URL;
    }

}


